__version__ = '0.1.0';
'use strict';
startup()
function startup() {
    connectButton = document.getElementById('connectButton');
    disconnectButton = document.getElementById('disconnectButton');
    sendButton = document.getElementById('sendButton');
    messageInputBox = document.getElementById('message');
    receiveBox = document.getElementById('receivebox');

    // Set event listeners for user interface widgets

    connectButton.addEventListener('click', connect, false);
    disconnectButton.addEventListener('click', disconnectPeers, false);
    sendButton.addEventListener('click', sendMessage, false);
}

let pc, Channel;
function connect(event) {
    pc = make_pc();
}

function make_pc(proactive = true) {
    const config = {
        iceServers: [{ urls: "stun:stun.ideasip.com" }]
    }
    log("生成pc，配置为:" + JSON.stringify(config) + "\tproactive:" + proactive);
    const pc = new RTCPeerConnection(config);

    pc.oniceconnectionstatechange = ice_connection_state_change;
    pc.onconnectionstatechange = connection_state_change;

    let self_candidates = [];
    pc.onicecandidate = ({ candidate }) => {
        if (candidate) {
            self_candidates.push(candidate)
            self_candidate_area.innerHTML = JSON.stringify(self_candidates);
        } else {
            log("本轮candidate生成完毕,共" + self_candidates.length + "个!")
            self_candidates = [];
        }
    }

    if (proactive) {
        Channel = pc.createDataChannel("Channel");
        Channel.onopen = handleChannelStatusChange;
        Channel.onclose = handleChannelStatusChange;

        Channel.onmessage = onMessage;

        pc.onnegotiationneeded = async () => {
            const offer = await pc.createOffer()
            await pc.setLocalDescription(offer);
            self_desc_area.innerHTML = JSON.stringify(pc.localDescription);
            log("self_description(offer)已生成")

        };
    }
    else {
        pc.ondatachannel = receiveChannelCallback;
    }
    return pc;
}



function handleChannelStatusChange(event) {
    if (Channel) {
        var state = Channel.readyState;

        if (state === "open") {
            messageInputBox.disabled = false;
            messageInputBox.focus();
            sendButton.disabled = false;
            disconnectButton.disabled = false;
            connectButton.disabled = true;
        } else {
            messageInputBox.disabled = true;
            sendButton.disabled = true;
            connectButton.disabled = false;
            disconnectButton.disabled = true;
        }
    }
}

function receiveChannelCallback(event) {
    Channel = event.channel;
    Channel.onmessage = onMessage;
    Channel.onopen = handleChannelStatusChange;
    Channel.onclose = handleChannelStatusChange;
}

function sendMessage() {
    var message = messageInputBox.value;
    Channel.send(message);

    messageInputBox.value = "";
    messageInputBox.focus();
}

function onMessage(event) {

    var el = document.createElement("p");
    var txtNode = document.createTextNode(event.data);

    el.appendChild(txtNode);
    receiveBox.appendChild(el);

}

function disconnectPeers() {

    // Close the RTCDataChannels if they're open.
    Channel.close();
    Channel = null;
    // Close the RTCPeerConnections
    pc.close();
    pc = null;
    // Update user interface elements
    connectButton.disabled = false;
    disconnectButton.disabled = true;
    sendButton.disabled = true;

    messageInputBox.value = "";
    messageInputBox.disabled = true;
}

// 手动交换信令
const self_desc_area = document.getElementById("self_description_str");
const self_candidate_area = document.getElementById("self_candidate_str");


const i_candi_textarea = document.getElementById("input_candidate_textarea");
const c_i_candi_btn = document.getElementById("confirm_input_candidate_btn");
c_i_candi_btn.addEventListener('click', c_i_candi);
c_i_candi_btn.disabled = true;
i_candi_textarea.onchange = () => { c_i_candi_btn.disabled = false; };

const i_desc_textarea = document.getElementById("input_description_textarea");
const c_i_desc_btn = document.getElementById("confirm_input_description_btn");
c_i_desc_btn.addEventListener('click', c_i_desc);
c_i_desc_btn.disabled = true;
i_desc_textarea.onchange = () => { c_i_desc_btn.disabled = false; };

async function c_i_candi() {
    const input_candidates = JSON.parse(i_candi_textarea.value);
    for (const i in input_candidates) {

        if (input_candidates[i]) {
            await pc.addIceCandidate(input_candidates[i]);
        }
    }
    log("远程candidates已加入")
}

async function c_i_desc() {
    const input_description = JSON.parse(i_desc_textarea.value);

    if (input_description.type == "offer") {
        // await pc.setLocalDescription({ type: "rollback" })
        pc = make_pc(proactive = false);
        await pc.setRemoteDescription(input_description);
        const answer = await pc.createAnswer()
        await pc.setLocalDescription(answer);
        self_desc_area.innerHTML = JSON.stringify(pc.localDescription);
        log("offer description已处理，answer description已生成，请回复");
    } else {
        await pc.setRemoteDescription(input_description);
        log("answer description已处理");
    }
}


const ice_connection_state = document.getElementById("iceConnectionState");
function ice_connection_state_change(event) {
    // https://developer.mozilla.org/en-US/docs/Web/API/RTCPeerConnection/iceConnectionState
    switch (pc.iceConnectionState) {
        case "new":
            ice_connection_state.innerHTML += "<p>正在检测网络...(" + pc.iceConnectionState + ")</p>";
            break;
        case "checking":
            ice_connection_state.innerHTML += "<p>收到远程candi，正在尝试连接...(" + pc.iceConnectionState + ")</p>";
            break;
        case "connected":
            ice_connection_state.innerHTML += "<p>与远程连接成功，后台依然实时监测(" + pc.iceConnectionState + ")</p>";
            break;
        case "completed":
            ice_connection_state.innerHTML += "<p>检测活动已经停止(" + pc.iceConnectionState + ")</p>";
            break;
        case "failed":
            ice_connection_state.innerHTML += "<p>与远程连接失败(" + pc.iceConnectionState + ")</p>";
            break;
        case "disconnected":
            ice_connection_state.innerHTML += "<p>与远程断开连接(" + pc.iceConnectionState + ")</p>";
            break;
        case "closed":
            ice_connection_state.innerHTML += "<p>candi服务已经关闭(" + pc.iceConnectionState + ")</p>";
            break;
        default:
            connection_state.innerHTML += "<p>收到未知状态:(" + pc.iceConnectionState + ")</p>";
    }
};
const connection_state = document.getElementById("ConnectionState");
function connection_state_change(event) {
    //   https://developer.mozilla.org/en-US/docs/Web/API/RTCPeerConnection/connectionState
    switch (pc.connectionState) {
        case "new":
            connection_state.innerHTML += "<p>收到新的candi信息(" + pc.connectionState + ")</p>";
            break;
        case "connecting":
            connection_state.innerHTML += "<p>尝试与远程candi连接中...(" + pc.connectionState + ")</p>";
            break;
        case "connected":
            connection_state.innerHTML += "<p>与所有candi连接成功(" + pc.connectionState + ")</p>";
            break;
        case "failed":
            connection_state.innerHTML += "<p>与至少一个candi连接失败(" + pc.connectionState + ")</p>";
            break;
        case "disconnected":
            connection_state.innerHTML += "<p>与至少一个candi断开连接(" + pc.connectionState + ")</p>";
            break;
        case "closed":
            connection_state.innerHTML += "<p>candi服务已经关闭(" + pc.connectionState + ")</p>";
            break;
        default:
            connection_state.innerHTML += "<p>收到未知状态:(" + pc.connectionState + ")</p>";
    }
}

function desc_state_change(event) {
    //   https://developer.mozilla.org/en-US/docs/Web/API/RTCPeerConnection/signalingState
    switch (pc.signalingState) {

    }
}